package com.fengze.business.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fengze.business.domain.*;
import com.fengze.business.mapper.*;
import com.fengze.common.annotation.AutoSetInsertValue;
import com.fengze.common.annotation.AutoSetUpdateValue;
import com.fengze.common.config.RuoYiConfig;
import com.fengze.common.exception.base.BaseException;
import com.fengze.common.utils.DateUtils;
import com.fengze.common.utils.StringUtils;
import com.fengze.common.utils.file.FileUploadUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fengze.business.service.IInquiryRecordService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * 询价记录Service业务层处理
 * 
 * @author lug
 * @date 2024-02-01
 */
@Service
public class InquiryRecordServiceImpl implements IInquiryRecordService 
{
    @Autowired
    private InquiryRecordMapper inquiryRecordMapper;

    @Autowired
    private SupplierLibraryMapper supplierLibraryMapper;

    @Autowired
    private InquiryManifestMapper inquiryManifestMapper;

    @Autowired
    private EarlyStageProjectMapper earlyStageProjectMapper;


    @Autowired
    private ProductsMapper productsMapper;

    /**
     * 查询询价记录
     * 
     * @param id 询价记录主键
     * @return 询价记录
     */
    @Override
    public InquiryRecord selectInquiryRecordById(Long id)
    {
        InquiryRecord inquiryRecord = inquiryRecordMapper.selectInquiryRecordById(id);

        List<InquiryManifest> manifestList = inquiryManifestMapper.selectByRecordId(id);

        inquiryRecord.setManifestList(manifestList);

        return inquiryRecord;
    }

    /**
     * 查询询价记录列表
     * 
     * @param inquiryRecord 询价记录
     * @return 询价记录
     */
    @Override
    public List<InquiryRecord> selectInquiryRecordList(InquiryRecord inquiryRecord)
    {
        return inquiryRecordMapper.selectInquiryRecordList(inquiryRecord);
    }

    /**
     * 新增询价记录
     * 
     * @param inquiryRecord 询价记录
     * @return 结果
     */
    @Override
    public int insertInquiryRecord(InquiryRecord inquiryRecord)
    {
        inquiryRecord.setCreateTime(DateUtils.getNowDate());
        return inquiryRecordMapper.insertInquiryRecord(inquiryRecord);
    }

    /**
     * 修改询价记录
     * 
     * @param inquiryRecord 询价记录
     * @return 结果
     */
    @Override
    public int updateInquiryRecord(InquiryRecord inquiryRecord)
    {
        inquiryRecord.setUpdateTime(DateUtils.getNowDate());
        return inquiryRecordMapper.updateInquiryRecord(inquiryRecord);
    }

    /**
     * 批量删除询价记录
     * 
     * @param ids 需要删除的询价记录主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteInquiryRecordByIds(Long[] ids)
    {

        inquiryManifestMapper.deleteByRecordIds(ids);
        return inquiryRecordMapper.deleteInquiryRecordByIds(ids);
    }

    /**
     * 删除询价记录信息
     * 
     * @param id 询价记录主键
     * @return 结果
     */
    @Override
    public int deleteInquiryRecordById(Long id)
    {
        return inquiryRecordMapper.deleteInquiryRecordById(id);
    }


    @AutoSetInsertValue
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertInquiryRecordWithFile(InquiryRecord inquiryRecord, MultipartFile file) throws BaseException {
        if (file != null && !file.isEmpty()) {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = null;
            try {
                fileName = FileUploadUtils.upload(filePath, file);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            inquiryRecord.setFileUrl(fileName);
        }

        EarlyStageProject earlyStageProject = earlyStageProjectMapper.selectEarlyStageProjectById(inquiryRecord.getEarlyStageProjectId());
        inquiryRecord.setProjectName(earlyStageProject.getName());
        // 查询供应商信息
        SupplierLibrary supplierLibrary = supplierLibraryMapper.selectSupplierLibraryById(inquiryRecord.getSupplierId());
        inquiryRecord.setSupplierName(supplierLibrary.getName());

        if(StringUtils.isEmpty(inquiryRecord.getManifest())){
            throw new BaseException("设备清单不能为空");
        }

        int insertCount = 0;
        ObjectMapper mapper = new ObjectMapper();
        try {



            CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class,InquiryManifest.class);
            List<InquiryManifest> manifests = mapper.readValue(inquiryRecord.getManifest(),listType);
            inquiryRecord.setInquiryNumber(manifests.size());
            insertCount = inquiryRecordMapper.insertInquiryRecord(inquiryRecord);
            for (InquiryManifest manifest : manifests) {
                Long productsId = manifest.getProductsId();
                Products products = productsMapper.selectProductsById(productsId);

                manifest.setProductsName(products.getName());
                manifest.setCategoryPids(products.getCategoryPids());
                manifest.setCategoryNames(products.getCategoryNames());
                manifest.setInquiryRecordId(inquiryRecord.getId());
                manifest.setStatus(1);
            }
            if (CollectionUtils.isNotEmpty(manifests)) {
                int count = inquiryManifestMapper.insertBatch(manifests);
                System.out.println(count);
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return insertCount;
    }


    @AutoSetUpdateValue
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateInquiryRecordWithFile(InquiryRecord inquiryRecord, MultipartFile file) throws BaseException {
        if (file != null && !file.isEmpty()) {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = null;
            try {
                fileName = FileUploadUtils.upload(filePath, file);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            inquiryRecord.setFileUrl(fileName);
        }

        SupplierLibrary supplierLibrary = supplierLibraryMapper.selectSupplierLibraryById(inquiryRecord.getSupplierId());
        inquiryRecord.setSupplierName(supplierLibrary.getName());
        EarlyStageProject earlyStageProject = earlyStageProjectMapper.selectEarlyStageProjectById(inquiryRecord.getEarlyStageProjectId());
        inquiryRecord.setProjectName(earlyStageProject.getName());
        //先删除原先的数据
        inquiryManifestMapper.deleteByRecordId(inquiryRecord.getId());

        if(StringUtils.isEmpty(inquiryRecord.getManifest())){
            throw new BaseException("设备清单不能为空");
        }
        int insertCount = 0;
        ObjectMapper mapper = new ObjectMapper();
        try {
            CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class,InquiryManifest.class);
            List<InquiryManifest> manifests = mapper.readValue(inquiryRecord.getManifest(),listType);
            inquiryRecord.setInquiryNumber(manifests.size());
            insertCount = inquiryRecordMapper.updateInquiryRecord(inquiryRecord);
            for (InquiryManifest manifest : manifests) {
                manifest.setInquiryRecordId(inquiryRecord.getId());
                manifest.setStatus(1);
            }
            int count = inquiryManifestMapper.insertBatch(manifests);
            System.out.println(count);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        return insertCount;
    }

    @Override
    public int countByStageProjectId(Long stageProjectId) {
        return inquiryRecordMapper.countByStageProjectId(stageProjectId);
    }
}
